import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin, Input} from 'antd';
import TextInput from 'Shared/components/TextInput';
import routes from './routes';
import {newOrUpdateValidator} from './validator';
import Return from '../common/Return';
import {injectIntl, language} from './intl';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {faultType, dutyUnitType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import {getDutyUnitsQuickly} from './api';
import SearchSelect from 'Shared/components/SearchSelect';
import DutyUnitSelectPanel from './DutyUnitSelectPanel';
import PartSelectPanel from './PartSelectPanel';
import SearchInput from 'Shared/components/SearchInput';

const faultTypeList = faultType.toList(language);
const FormItem = Form.Item;
export class NewPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        data: [],
        showDutyUnit: false,
        showSupplier: false,
        showPart: false
    }
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    labelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.code}`;
        return '';
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        this.setState({
            loading: false,
            data: record,
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const data = this.state.data;
        const isValid = newOrUpdateValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        this.props.onSubmit(data)
            .then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSearchDutyUnit = value =>
        getDutyUnitsQuickly({
            filter: value,
            type: dutyUnitType.责任单位
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    onSelectDutyUnit = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                dutyUnitId: data.id,
                dutyUnitCode: data.code,
                dutyUnitName: data.name
            }),
            showDutyUnit: false,
            hasOperat: true
        });
    }
    onClickDutyUnit = () => {
        this.setState({showDutyUnit: true});
    }
    onCloseDutyUnit = () => {
        this.setState({showDutyUnit: false});
    }
    
    onSearchSupplier = value =>
        getDutyUnitsQuickly({
            filter: value,
            type: dutyUnitType.索赔供应商
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    onSelectSupplier = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                supplierId: data.id,
                supplierCode: data.code,
                supplierName: data.name
            }),
            showSupplier: false,
            hasOperat: true
        });
    }
    onClickSupplier = () => {
        this.setState({showSupplier: true});
    }
    onCloseSupplier = () => {
        this.setState({showSupplier: false});
    }
    onSelectPart = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                partId: data.id,
                partCode: data.code,
                partName: data.name
            }),
            showPart: false,
            hasOperat: true
        });
    }
    onClickPart = () => {
        this.setState({showPart: true});
    }
    onClosePart = () => {
        this.setState({showPart: false});
    }
    render() {
        const {data, isValidate} = this.state;
        const {formatMessage} = this.props.intl;
        if(this.props.brands.length === 1 && !this.props.id) {
            data.brandId = this.props.brands[0].value;
            data.brandName = this.props.brands[0].text;
        }
        const dutyUnitInfo = data.dutyUnitId ? {
            id: data.dutyUnitId,
            code: data.dutyUnitCode,
            name: data.dutyUnitName,
        } : null;
        const supplierInfo = data.supplierId ? {
            id: data.supplierId,
            code: data.supplierCode,
            name: data.supplierName,
        } : null;
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'addPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={isValidate && !data.brandId ? 'error' : null}
                                        required={!data.id}>
                                        {this.props.id ? `(${data.brandCode})${data.brandName}` : <WrappedSelect
                                            name="brandId"
                                            options={this.props.brands}
                                            value={data.brandId}
                                            onChange={this.onChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'addPanel.data.faultType',
                                            defaultMessage: '故障类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={isValidate && !data.faultType ? 'error' : null}
                                        required>
                                        <WrappedSelect
                                            name="faultType"
                                            value={data.faultType}
                                            options={faultTypeList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                {data.id ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dutyUnitId',
                                            defaultMessage: '责任单位'
                                        })}
                                        {...FORM_OPTIONS.item} >
                                        {data.dutyUnitCode}
                                    </FormItem>
                                </Col> : <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dutyUnitId',
                                            defaultMessage: '责任单位'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={!data.dutyUnitId && this.state.validate ? 'error' : null}
                                        required>
                                        {
                                            data.brandId ? <SearchSelect
                                                value={dutyUnitInfo}
                                                placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.form.dutyUnitId.placeholder',
                                                    defaultMessage: '请输入责任单位名称或编号进行查询'
                                                })}
                                                onSelect={this.onSelectDutyUnit}
                                                onSearch={this.onSearchDutyUnit}
                                                keyIndex="id"
                                                labelMap={this.labelMap}
                                                onClickSearchBtn={this.onClickDutyUnit} /> : <TextInput name="dutyUnitId"
                                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.dealerComp.placeholder',
                                                    defaultMessage: '请先选择品牌'
                                                })} />
                                        }
                                    </FormItem>
                                </Col>
                                }
                                {
                                    data.id ? <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.supplierId',
                                                defaultMessage: '供应商'
                                            })}
                                            {...FORM_OPTIONS.item} >
                                            {data.supplierCode}
                                        </FormItem>
                                    </Col> : <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.supplierId',
                                                defaultMessage: '供应商'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={!data.supplierId && this.state.validate ? 'error' : null}
                                            required>
                                            {
                                                data.brandId ? <SearchSelect
                                                    value={supplierInfo}
                                                    placeholder={this.props.intl.formatMessage({
                                                        id: 'newPanel.form.supplierId.placeholder',
                                                        defaultMessage: '请输入供应商名称或编号进行查询'
                                                    })}
                                                    onSelect={this.onSelectSupplier}
                                                    onSearch={this.onSearchSupplier}
                                                    keyIndex="id"
                                                    labelMap={this.labelMap}
                                                    onClickSearchBtn={this.onClickSupplier} /> : <TextInput name="supplierId"
                                                    value={''} disabled placeholder={this.props.intl.formatMessage({
                                                        id: 'newPanel.dealerComp.placeholder',
                                                        defaultMessage: '请先选择品牌'
                                                    })} />}
                                            
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partId',
                                        defaultMessage: '判定零件编号'
                                    })} {...FORM_OPTIONS.item} >
                                        {
                                            data.brandId ? <SearchInput
                                                disabled={true}
                                                value={data.partCode}
                                                id={data.partId}
                                                onClickSearchBtn={this.onClickPart} /> : <TextInput name="supplierId"
                                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.dealerComp.placeholder',
                                                    defaultMessage: '请先选择品牌'
                                                })} />
                                        }
                                        
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.transmission',
                                        defaultMessage: '判定变速箱型号'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="transmission"
                                            value={data.transmission}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.remark',
                                        defaultMessage: '备注'
                                    })}{...FORM_ROW_OPTIONS.item}><TextInput
                                            name="remark"
                                            type="textarea"
                                            value={data.remark}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'addPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                    {
                        this.state.showDutyUnit &&
                        <DutyUnitSelectPanel
                            type={dutyUnitType.责任单位}
                            isDutyUnit={true}
                            selectKey={data.dutyUnitId}
                            onCancel={this.onCloseDutyUnit}
                            onSelect={this.onSelectDutyUnit} />
                    }
                    {
                        this.state.showSupplier &&
                        <DutyUnitSelectPanel
                            type={dutyUnitType.索赔供应商}
                            selectKey={data.supplierId}
                            onCancel={this.onCloseSupplier}
                            onSelect={this.onSelectSupplier} />
                    }
                    {
                        this.state.showPart &&
                        <PartSelectPanel
                            isDutyUnit={false}
                            brandId={data.brandId}
                            selectKey={data.partId}
                            onCancel={this.onClosePart}
                            onSelect={this.onSelectPart} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    data: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    brands: PropTypes.array,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch, onSubmit} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id,
            currency: item.currency
        })) : [];
        return brands;
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    brands: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onSubmit(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
